/**
 * 
 */
package com.effectivsocial.extension.plugin;

import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import com.effectivsocial.domain.TilesDefinitions;
import com.effectivsocial.service.api.ViewDefinitionService;
import com.thoughtworks.xstream.XStream;

/**
 * @author Dhrubo
 * 
 */
@Named
@Slf4j
public class ViewDefinitionLoaderPlugin implements StartupPlugin {

	private final String FILE_PATTERN = "classpath:/META-INF/tiles/tiles-*.xml";
	
	@Inject
	private ViewDefinitionService viewDefinitionService;
	

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.effectivcrm.extension.plugin.StartupPlugin#preProcess(org.springframework
	 * .context.ApplicationContext)
	 */
	public void preProcess(ApplicationContext ctx) {
		log.info("Deleting all view definitions");
		
		
		viewDefinitionService.deleteAllAssociatedLinkGroups();
		viewDefinitionService.purgeAll();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.effectivcrm.extension.plugin.StartupPlugin#process(org.springframework
	 * .context.ApplicationContext)
	 */
	public void process(ApplicationContext ctx) {
		
				
		Resource[] resources;
		try {
			resources = ctx.getResources(FILE_PATTERN);

			XStream xstream = new XStream();
			for (Resource resource : resources) {
				if(log.isInfoEnabled()){
					log.info("## Processing resource = {}", resource);
				}
				
				xstream.processAnnotations(new Class[] { TilesDefinitions.class });
				TilesDefinitions definitions = (TilesDefinitions) xstream
						.fromXML(resource.getInputStream());
				
				if(log.isInfoEnabled()){
					log.info("## Definitions  = {}", definitions.getDefinitions());
				}
				
								
				viewDefinitionService.save(definitions.getDefinitions());
			}

		} catch (IOException e) {
			log.error("Error", e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.effectivcrm.extension.plugin.StartupPlugin#postProcess(org.
	 * springframework.context.ApplicationContext)
	 */
	public void postProcess(ApplicationContext ctx) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.effectivcrm.extension.plugin.StartupPlugin#getOrder()
	 */
	public int getOrder() {
		// TODO Auto-generated method stub
		return 700;
	}

}
